package com.shi.yoyoshop.controller;

import com.shi.yoyoshop.bean.Goods;
import com.shi.yoyoshop.bean.Item;
import com.shi.yoyoshop.bean.Order;
import com.shi.yoyoshop.service.GoodsService;
import com.shi.yoyoshop.service.ItemService;
import com.shi.yoyoshop.service.OrderService;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class PayController {

    @Resource
    private OrderService orderService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private ItemService itemService;

    @GetMapping("/index/topay")
    public String toPay(HttpServletRequest request, @RequestParam("orderid") Integer orderId) {
        Order order = orderService.getOrderById(orderId);
        request.getSession().setAttribute("order", order);
        return "/index/pay.jsp";
    }

    /**
     * 订单支付
     *
     * @param request
     * @param payType
     * @param name
     * @param phone
     * @param address
     * @return
     */
    @Transactional
    @PostMapping("/index/pay")
    public String pay(HttpServletRequest request, @RequestParam("paytype") Integer payType, String name, String phone, String address) {
        Order order = (Order) request.getSession().getAttribute("order");
        List<Item> itemList = itemService.getItemListByOrderId(order.getId());
        // 提交订单
        // 判断是否每个商品都库存充足
        for (Item item : itemList) {
            Integer goodId = item.getGoodId();
            Integer amount = item.getAmount();
            Goods goods = goodsService.getGoodsById(goodId);
            // 库存不足
            if (goods.getStock() < amount) {
                request.setAttribute("msg", goods.getName() + ": 库存不足");
                return "/index/payok.jsp";
            }
        }
        // 修改订单的状态
        order.setStatus(2);
        order.setPaytype(payType);
        order.setName(name);
        order.setPhone(phone);
        order.setAddress(address);
        orderService.updateOrderById(order);
        request.setAttribute("msg", "支付成功！");
        // 提交订单，移除session中的购物车信息
        request.getSession().setAttribute("order", null);
        return "/index/payok.jsp";
    }
}
